# -*- coding: utf-8 -*-

from localTest import *
import _pg

BUFFER_DOCUMENT_SIZE = "1400"
BUFFER_WORDS_SIZE = "1400"

class InterfaceDB:
    """Provides an interface for the database (DB) containing the corpus (all the documents) in which to apply the Latent Semantic Analysis (LSA).
    It also provides functions to a separate virtual test DB defined by constants in the class localTest.
    The test mode is the one used in the doctest (for more info see http://docs.python.org/library/doctest.html?highlight=doctest#module-doctest).
     """
    local_test = None 
    """Local test data"""
    db = None
    """Connection to the database"""
    word_buffer = None
    """Buffer for storing documents"""
    doc_buffer = None
    """Buffer for storing"""
    
    def get_next_new_doc_id(self):
        """Retrieves a unique identifier of the next new document in the database.
        After being retrieved the document is marked as not new anymore. """
        if self.doc_buffer == None or len(self.doc_buffer) == 0 :
            resultats  = self.db.query("SELECT document.doc_id FROM document WHERE document.est_nouveau = TRUE AND document.doc_date_last_index IS NOT NULL "+self.extra_db_parameters +" LIMIT "+BUFFER_DOCUMENT_SIZE)
            if resultats.ntuples() == 0:
                return 0
            else:
                a_query = ""
                for resultat in resultats.dictresult() :
                    a_query += "UPDATE document SET est_nouveau = FALSE WHERE doc_id ="+str(resultat['doc_id'])+"; "
                self.db.query(a_query)
                self.doc_buffer = resultats.dictresult()
        doc_id  = self.doc_buffer[0]['doc_id']
        del self.doc_buffer[0]
        return doc_id
	
    def get_words(self,doc_id):
        """Returns the complete string of the document identified by the doc_id parameter."""
        doc_id = int(doc_id)
        if self.word_buffer.get(doc_id) != None : 
            return self.word_buffer.get(doc_id)
        resultats  = self.db.query("SELECT mi_racine FROM mot_indexe WHERE mot_indexe.doc_id = "+str(doc_id) )
        if resultats.ntuples() == 0 :
            raise Exception('Pas de mots trouvés avec cet id !!')
        the_string = "";
        for resultat in resultats.dictresult() :
            the_string += " "+resultat['mi_racine']
        if len(self.word_buffer) + 1 < int(BUFFER_WORDS_SIZE) : 
            self.word_buffer[doc_id] = the_string
        else : 
            self.word_buffer = {}
            self.word_buffer[doc_id] = the_string
        return the_string
	
    def __test_get_words(self,doc_id):
        """Private method equivalent to get_words() in test context."""
        return self.local_test.data[int(doc_id)]
        
    def __test_get_next_new_doc_id(self):
        """Private method equivalent to get_next_new_doc_id() in test context."""    
        if len( self.local_test.new_data_indexes ) == 0 :
            return 0
        else:
            doc_id  = self.local_test.new_data_indexes[-1]
            self.local_test.new_data_indexes.remove(doc_id)
            return doc_id
        
    def __init__(self,test_mode = None, extra_db_parameters = None):
        """
        Initialize the interface to the database.
        When true the test_mode parameter will provide access to a virtual test DB.
        All the contents in the test DB are defined by constants in the class localTest.
        The extra_db_parameters parameter is only used when not in test mode.
        The extra_db_parameters parameter will be used by get_words() and get_next_new_doc_id() when performing database queries.  
        """
        if test_mode !=  None:
            self.local_test = LocalTest()
            self.get_next_new_doc_id = self.__test_get_next_new_doc_id
            self.get_words = self.__test_get_words
        else: 
            if extra_db_parameters != None :
                self.extra_db_parameters = " AND lang_id ="+ extra_db_parameters['lang']
            self.word_buffer = {}
            self.db=_pg.connect('projetdocument','92.243.7.188',5432,None,None,'michel','granularite')
            

